<template>
  <div class="login-container">
    <div class="login-title">登录</div>
    <a-form :form="form" class="user-layout-login">
      <a-form-item class="input-with-label">
        <span class="input-label">账号</span>
        <a-input v-decorator="['username', {...validatorRules.username,
          initialValue: accountInfo.username}]" size="large" placeholder="请输入后台账号">
        </a-input>
      </a-form-item>
      <a-form-item class="input-with-label">
        <span class="input-label">密码</span>
        <a-input
          v-decorator="['password', {...validatorRules.password,initialValue: accountInfo.password}]"
          size="large" type="password" placeholder="请输入登录密码">
        </a-input>
      </a-form-item>
      <a-form-item class="checkbox-container">
        <a-checkbox v-decorator="[
            'rememberMe',
            { initialValue: true, valuePropName: 'checked' },
          ]">记住密码</a-checkbox>
      </a-form-item>
      <a-form-item>
        <a-button class="login-button" size="large" type="primary" htmlType="submit"
          :loading="logging" @click.stop.prevent="handleSubmit" :disabled="logging">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { timeFix } from '@/utils/util'
import JsEncrypt from 'jsencrypt'
import { mapActions } from 'vuex'
export default {
  name: 'Login',
  components: {},
  data () {
    return {
      logging: false,
      accountInfo: {
        username: '',
        password: ''
      },
      validatorRules: {
        username: {
          rules: [
            { required: true, message: '请输入用户名!' }
          ]
        },
        password: {
          rules: [
            { required: true, message: '请输入密码!' }
          ]
        }
      },
      form: this.$form.createForm(this)
    }
  },
  created () {
    this.getAccountInfo()
  },
  methods: {
    ...mapActions(['Login']),
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.logging = true
          let username = values.username
          let password = values.password
          if (values.rememberMe) {
            const info = {
              username,
              password
            }
            this.$cookies.set('ACCOUNT_INFO', JSON.stringify(info))
          } else {
            this.$cookies.remove('ACCOUNT_INFO')
          }
          const publicKey = await this.getPublickey()
          const mix = this.rsaEncrypt(publicKey, password)
          const params = {
            username,
            mix
          }
          this.Login(
            { ...params }
          )
            .then((res) => {
              if (this.isSuccess(res)) {
                this.logging = true
                this.loginSuccess()
              } else {
                this.logging = false
              }
            })
            .catch((err) => {
              this.logging = false
              this.requestFailed(err)
            })
        }
      })
    },
    // 获取公钥
    getPublickey () {
      return new Promise((resolve, reject) => {
        this.$get(this.$api.upms.upms.publicKey, {}, {}).then((res) => {
          if (this.isSuccess(res)) {
            resolve(res.data)
          } else {
            this.logging = false
            reject(new Error('公钥获取失败!'))
          }
        })
      })
    },
    // 密码加密
    rsaEncrypt (publickey, data) {
      var jse = new JsEncrypt()
      jse.setPublicKey(publickey)
      return jse.encrypt(data)
    },
    loginSuccess () {
      console.log('登录成功')
      this.$router.push({ name: 'HomeDef' })
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`
      })
    },
    requestFailed (err) {
      this.$notification['error']({
        message: '登录失败',
        description:
          ((err.response || {}).data || {}).message ||
          err.message ||
          err.resultHint ||
          '请求出现错误，请稍后再试',
        duration: 4
      })
      this.loginBtn = false
    },
    // 判断是否存在账号信息cookies，存在则获取
    getAccountInfo () {
      let accountInfo = this.$cookies.get('ACCOUNT_INFO')
      if (accountInfo) {
        this.accountInfo = { ...accountInfo }
      }
    }
  },
  computed: {}
}
</script>
<style lang="less" >
.login-container {
  .ant-input-lg {
    border: 0;
    border-radius: 32px;
    height: 65px;
    font-size: 24px;
    background-color: #f6f7fb;
    padding: 0 32px;
  }
  .ant-input-lg:placeholder {
    font-size: 24px;
    color: #b4b4b4;
  }
  .ant-input:hover {
    background-color: #f6f7fb;
  }
  .ant-col {
    height: 90px;
  }
  .ant-form-item-with-help {
    margin-bottom: 12px;
    .ant-form-explain {
      margin-left: 20px;
    }
  }
  .login-title {
    margin-left: 6px;
    margin-bottom: 42px;
    font-family: 'SHCN-Bold';
    font-size: 36px;
    background: linear-gradient(to bottom, #2edbdb, #2f9ae8);
    -webkit-background-clip: text;
    color: transparent;
  }
  .checkbox-container {
    margin-top: -20px;
    margin-left: 20px;
    margin-bottom: 30px;
    .ant-col {
      height: auto;
    }
    .ant-checkbox-wrapper {
      font-size: 18px;
      color: #2face4;
    }
    .ant-checkbox-checked .ant-checkbox-inner {
      border-color: #2face4;
    }
    .ant-checkbox-checked .ant-checkbox-inner::after {
      border-color: #2face4;
    }
  }
  .login-button {
    width: 100%;
    height: 65px;
    border-radius: 32px;
    font-size: 24px;
    font-weight: bold;
    background-image: linear-gradient(to bottom, #2edbdb, #2f9ae8);
    text-decoration: none;
    outline: none;
    border: 0;
  }
  
  .input-with-label {
    position: relative;
  }
  
  .input-label {
    position: absolute;
    left: -45px;
    top: -15px;
    font-size: 16px;
    color: #2face4;
    z-index: 1;
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>
